package cn.stylefeng.guns.modular.controller;

import cn.stylefeng.guns.base.auth.annotion.Permission;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.log.BussinessLog;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.dto.FuzzySearchSframeDto;
import cn.stylefeng.guns.modular.dto.ScheduleFrameDto;
import cn.stylefeng.guns.modular.dto.ScheduleFrameItemDto;
import cn.stylefeng.guns.modular.entity.ScheduleFrame;
import cn.stylefeng.guns.modular.entity.ScheduleFrameItem;
import cn.stylefeng.guns.modular.entity.SframeItemTimeLimit;
import cn.stylefeng.guns.modular.service.ScheduleFrameItemService;
import cn.stylefeng.guns.modular.service.ScheduleFrameService;
import cn.stylefeng.guns.modular.utils.UserMessage;
import cn.stylefeng.guns.modular.utils.WeekBetweenCount;
import cn.stylefeng.guns.modular.wapper.MyScheduleFrameWrapper;
import cn.stylefeng.guns.modular.wapper.MyscheduleformWrapper;
import cn.stylefeng.guns.sys.core.constant.Const;
import cn.stylefeng.guns.sys.core.constant.dictmap.UserDict;
import cn.stylefeng.guns.sys.modular.system.model.UserDto;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.ErrorManager;

@Controller
@RequestMapping("/myScheduleFrame")
public class MyScheduleFrameController extends BaseController {
    @Autowired
    private ScheduleFrameService scheduleFrameService;
    @Autowired
    private ScheduleFrameItemService scheduleFrameItemService;



    /**
     * 加载我的日程框架页面
     * @return
     */
    @RequestMapping("/showMyScheduleFrame")
    public String toMyScheduleFrame(){
        return "/scheduleframe/myScheduleFrame.html";
    }

    /**
     * 显示所有日程框架
     */
    @RequestMapping(value = "/showMyScheduleFrame" ,method = RequestMethod.POST)
    @ResponseBody
    public Object showMyScheduleFrame(FuzzySearchSframeDto fuzzySearchSframeDto){
        String startDate=null;
        String stopDate=null;
        System.out.println("================="+fuzzySearchSframeDto);
        if (fuzzySearchSframeDto.getTimeLimit()!=null&fuzzySearchSframeDto.getTimeLimit()!=""){
             startDate= fuzzySearchSframeDto.getTimeLimit().split("-")[0];
             stopDate= fuzzySearchSframeDto.getTimeLimit().split("-")[1];
        }

        if (fuzzySearchSframeDto.getSframeName()!=null&fuzzySearchSframeDto.getSframeName()!=""){
            fuzzySearchSframeDto.setSframeName(fuzzySearchSframeDto.getSframeName().trim());
        }

       fuzzySearchSframeDto.setStartDate(startDate);
       fuzzySearchSframeDto.setStopDate(stopDate);
        System.out.println("================="+fuzzySearchSframeDto);
        long userId = UserMessage.getUserId();
        Page<Map<String, Object>> scheduleFrame =scheduleFrameService.fuzzySearchSframe(fuzzySearchSframeDto,userId);

        Page wrapped = new MyScheduleFrameWrapper(scheduleFrame).wrap();
        LayuiPageInfo layuiPageInfo =LayuiPageFactory.createPageInfo(wrapped);
        System.out.println("================================"+layuiPageInfo);
        return layuiPageInfo;
    }



    /**
     * 添加框架
     * 加载添加框架页面
     * @return
     */
    @RequestMapping("/addSframe")
    public String addScheduleFrame(){
        return "/scheduleframeItem/frameItem.html";
    }

    /**
     * 保存日程框架信息
     *  先保存框架信息
     *  再保存框架项信息
     *  再根据框架名称找到框架id,再set到框架项的sframeId中
     */
    @RequestMapping("/saveSframe")
    @ResponseBody
    public ResponseData saveSframe(ScheduleFrameItemDto scheduleFrameItemDto,ScheduleFrameDto scheduleFrameDto) {
        System.out.println("\n\n\n\n\n\n"+"=============="+scheduleFrameDto);
        System.out.println("\n\n\n\n\n\n"+"=============="+scheduleFrameItemDto);
        /**
         * 获得当前登陆者的信息
         */
        long userId =UserMessage.getUserId();

        System.out.println("===========userId="+userId);
        ScheduleFrame scheduleFrame =new ScheduleFrame();
        //设置sframe的值
        scheduleFrame.setSframeName(scheduleFrameDto.getSframeName());
        scheduleFrame.setUserId(userId);
        scheduleFrame.setOrganization(scheduleFrameDto.getOrganization());
        scheduleFrame.setStartDate(WeekBetweenCount.formatDate(scheduleFrameDto.getStartDate()));
        scheduleFrame.setStopDate(WeekBetweenCount.formatDate(scheduleFrameDto.getStopDate()));
        if (scheduleFrameDto.getDraft()==null){
            scheduleFrameDto.setDraft("off");
        }
        if (scheduleFrameDto.getPublish()==null){
            scheduleFrameDto.setPublish("off");
        }
        scheduleFrame.setPublish(scheduleFrameDto.getPublish());
        scheduleFrame.setFrameDraft(scheduleFrameDto.getDraft());
        int weeks=WeekBetweenCount.weeksBetweenDays(scheduleFrameDto.getStartDate(),scheduleFrameDto.getStopDate());
        scheduleFrame.setWeekCount(""+weeks);
        scheduleFrame.setCreatTime(new Date());
        //保存框架信息
        //  查看同一个用户Id是否重名
        ScheduleFrame scheduleFrameByName=scheduleFrameService.selectScheduleFrameByName(scheduleFrameDto.getSframeName(),userId);
        SimpleDateFormat sdf= new SimpleDateFormat("hh:mm:ss");
        Date startTime=null;
        Date stopTime=null;

        if (scheduleFrameByName==null) {
            scheduleFrameService.saveScheduleFrame(scheduleFrame);
            //设置sframeItem的值
            for (int i=0;i<scheduleFrameItemDto.getScheduleItemName().size();i++){
                ScheduleFrameItem scheduleFrameItem =new ScheduleFrameItem();
                scheduleFrameItem.setSerialNumber(scheduleFrameItemDto.getSerial().get(i));
                scheduleFrameItem.setSframeItemName(scheduleFrameItemDto.getScheduleItemName().get(i));


                try {
                    startTime= sdf.parse(scheduleFrameItemDto.getStartTime().get(i));
                    stopTime =sdf.parse(scheduleFrameItemDto.getStopTime().get(i));
                } catch (ParseException e) {
                    e.printStackTrace();
                }


                scheduleFrameItem.setStartTime(startTime);
                scheduleFrameItem.setStopTime(stopTime);
                //根据框架项名字查找框架
               ScheduleFrame scheduleFrameAfterSave= scheduleFrameService.selectScheduleFrameByName(scheduleFrameDto.getSframeName(),userId);
               //遍历设置框架id
                scheduleFrameItem.setSframeId(scheduleFrameAfterSave.getSframeId());
                //遍历保存框架项
              int  saveRows=  scheduleFrameItemService.saveFrameItem(scheduleFrameItem);
                //判断是否保存成功
                if (saveRows==1){
                    System.out.println("保存成功！");

                }else {
                    System.out.println("保存失败！");
                }
            }
            return SUCCESS_TIP;
        }
        else {
            System.out.println("框架名字不能相同");
            return  ResponseData.error(400,"框架名字不能相同!");

        }
    }

    /**
     *加载修改框架页面
     * @return
     */
    @RequestMapping("/reviseSframe")
    public String loadReviseSframe(String sframeId,Model model){
        //根据sframeId得到框架项

     ScheduleFrame scheduleFrame=   scheduleFrameService.selectScheduleFrameById(Integer.parseInt(sframeId));


        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String startDate=simpleDateFormat.format( scheduleFrame.getStartDate());
        String stopDate=simpleDateFormat.format(scheduleFrame.getStopDate());

        System.out.println("======123========="+scheduleFrame);

        model.addAttribute("scheduleFrame",scheduleFrame);
        model.addAttribute("startDate",startDate);
        model.addAttribute("stopDate",stopDate);
        System.out.println("==============="+scheduleFrame);
        return "/scheduleframe/reviseSframe.html";
    }

    /**
     *加载修改框架页面信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/reviseSframe1",method = RequestMethod.POST)
    public JSONObject reviseSframe(String sframeId){

        System.out.println("=============123123========"+sframeId);
        //根据sframeId得到框架项
        ScheduleFrame scheduleFrame=   scheduleFrameService.selectScheduleFrameById(Integer.parseInt(sframeId));

        JSONObject result = JSONObject.parseObject(JSON.toJSONString(scheduleFrame));
        System.out.println("======123========="+result);
        return result;
    }


    /**
     * 选中框架进行修改后保存日程框架信息
     *  先收集数据
     *  再保存修改信息
     *
     */
    @RequestMapping("/changeAndSaveSframe")
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public ResponseData changeAndSaveSframe(ScheduleFrameItemDto scheduleFrameItemDto,ScheduleFrameDto scheduleFrameDto,HttpServletRequest request) {
        System.out.println("=================="+scheduleFrameItemDto);
        System.out.println("=================="+scheduleFrameDto);
        int sframeId  = Integer.parseInt(request.getParameter("sframeId"));
        /**
         * 获得当前登陆者的信息
         */
        long userId =UserMessage.getUserId();
        ScheduleFrame scheduleFrame =new ScheduleFrame();
        //设置sframe的值
        scheduleFrame.setSframeId(sframeId);
        scheduleFrame.setSframeName(scheduleFrameDto.getSframeName());
        scheduleFrame.setUserId(userId);
        scheduleFrame.setOrganization(scheduleFrameDto.getOrganization());
        scheduleFrame.setStartDate(WeekBetweenCount.formatDate(scheduleFrameDto.getStartDate()));
        scheduleFrame.setStopDate(WeekBetweenCount.formatDate(scheduleFrameDto.getStartDate()));
        //保存框架信息
        //  查看同一个用户Id是否重名
        ScheduleFrame scheduleFrameByName=scheduleFrameService.selectScheduleFrameByName(scheduleFrameDto.getSframeName(),userId);
        System.out.println("==========123================="+scheduleFrameByName);
        if (scheduleFrameByName.getSframeId()==sframeId) {
            //就是框架名称没有改
            scheduleFrameService.updateScheduleFrame(scheduleFrame);
            //先根据sframeId删除框架项信息
            scheduleFrameItemService.delectSFrameItemBySframeId(sframeId);
            //设置sframeItem的值
            System.out.println("=====count========"+scheduleFrameItemDto.getScheduleItemName().size());

            SimpleDateFormat sdf= new SimpleDateFormat("hh:mm:ss");
            Date startTime=null;
            Date stopTime=null;
            for (int i=0;i<scheduleFrameItemDto.getScheduleItemName().size();i++){
                ScheduleFrameItem scheduleFrameItem =new ScheduleFrameItem();
                scheduleFrameItem.setSframeId(sframeId);
                scheduleFrameItem.setSerialNumber(scheduleFrameItemDto.getSerial().get(i));
                scheduleFrameItem.setSframeItemName(scheduleFrameItemDto.getScheduleItemName().get(i));



                try {
                    startTime= sdf.parse(scheduleFrameItemDto.getStartTime().get(i));
                    stopTime =sdf.parse(scheduleFrameItemDto.getStopTime().get(i));
                } catch (ParseException e) {
                    e.printStackTrace();
                }


                scheduleFrameItem.setStartTime(startTime);
                scheduleFrameItem.setStopTime(stopTime);






                System.out.println("=========1234============"+scheduleFrameItem);
                //遍历保存框架项
                int  saveRows=  scheduleFrameItemService.saveFrameItem(scheduleFrameItem);

                //判断是否保存成功
                if (saveRows==1){
                    System.out.println("修改成功！");


                }else {
                    System.out.println("保存失败！");
                    return ResponseData.error("保存失败！");
                }
            }
            return SUCCESS_TIP;
        }
        else {
            System.out.println("框架名字不能相同!");
            return  ResponseData.error("框架名字不能相同！");

        }
    }

    /**
     * 加载复制框架页面
     * @return
     */
    @RequestMapping("loadCopySframe")
    public String loadCopySframe(String sframeId ,Model model ){
        model.addAttribute("sframeId",sframeId);

        return "/scheduleframe/copyframe.html";
    }

    /**
     * 复制日程框架
     * @param sframeName
     * @param sframeId
     * @return
     */
    @RequestMapping("copySframe")
    @ResponseBody
    public String copySframe(String sframeName,String sframeId ){
        //得到选中的框架Id
        System.out.println("==============="+sframeName);
        System.out.println("==============="+sframeId);

        /**
         * 获得当前登陆者的信息
         */
        LoginUser user = LoginContextHolder.getContext().getUser();
        long userId =user.getId();
        //根据选中的框架id得到框架信息
        ScheduleFrame scheduleFrame= scheduleFrameService.selectScheduleFrameById(Integer.parseInt(sframeId));
        scheduleFrame.setSframeName(sframeName);

        //保存框架信息
        //  查看同一个用户Id是否重名
        ScheduleFrame scheduleFrameByName=scheduleFrameService.selectScheduleFrameByName(sframeName,userId);

        if (scheduleFrameByName!=null) {
            System.out.println("框架名字不能相同");
            return  "复制失败！";
        }

            //若没有重名，保存复制的框架信息
            scheduleFrameService.saveScheduleFrame(scheduleFrame);
            //查看刚插入的框架信息
            ScheduleFrame scheduleFrameNew=scheduleFrameService.selectScheduleFrameByName(sframeName,userId);
            List<ScheduleFrameItem> scheduleFrameItems = scheduleFrameItemService.selectSframeItemBySframeId(Integer.parseInt(sframeId));
            //遍历设置复制sframeItem的值
            for (ScheduleFrameItem scheduleFrameItem : scheduleFrameItems) {
                scheduleFrameItem.setSframeId(scheduleFrameNew.getSframeId());
                //遍历保存框架项
                int saveRows = scheduleFrameItemService.saveFrameItem(scheduleFrameItem);
                //判断是否保存成功
                if (saveRows != 1) {
                    System.out.println("保存失败！");
                    return "复制失败！";

                }
            }
        return "复制成功！";
    }

    /**
     * 设置为框架是否为草稿
     * @param request
     * @return
     */
    @RequestMapping("/setDraft")
    public String setDraft(HttpServletRequest request){
       String frameDraft=  request.getParameter("frameDraft");
       int sframeId= Integer.parseInt(request.getParameter("sframeId"));
       //设置框架草稿属性的值
      int rows = scheduleFrameService.setSframeDraft(frameDraft,sframeId);
       return null;

    }

    /**
     * 设置为框架是否发布（发布后不能进行修改）
     * @param request
     * @return
     */
    public String setPublish(HttpServletRequest request){
       String publish= request.getParameter("publish");
      int sframeId= Integer.parseInt(request.getParameter("sframeId"));
      //设置框架发布属性的值
       int rows= scheduleFrameService.setPublish(publish,sframeId);

        return null;
    }



    /**
     *基于个哪日程框架创建日程表
     * @return
     */
    @RequestMapping(value = "/selectframe" )
    public String addScheduleForm(){
        return "/scheduleframe/selectframe.html";
    }

    /**
     * 返回所有框架姓名(加载所有框架名字)
     * @return
     */
    @RequestMapping(value = "/selectAllframeName" )
    @ResponseBody
    public List<ScheduleFrame> selectAllframeName(){
        /**
         * 获得当前登陆者的信息
         */
        LoginUser user = LoginContextHolder.getContext().getUser();
        long userId =user.getId();
       List<ScheduleFrame> scheduleFrames= scheduleFrameService.selectAllScheduleFrame(userId);
        return scheduleFrames;

    }

    /**
     * 根据选中的框架Id删除并删除其框架项
     * @param sframeId
     * @return
     */
    @RequestMapping("deleteSframeBySframeId")
    @ResponseBody
    public String deleteSframeBySframeId(String sframeId){
        System.out.println("=-======time: 20000================"+sframeId);
       int row1= scheduleFrameItemService.delectSFrameItemBySframeId(Integer.parseInt(sframeId));
        int row2= scheduleFrameService.deleteScheduleFrameById(Integer.parseInt(sframeId));
        if (row2==1){
            return "日程框架删除成功！";
        }
        else {
            return "日程框架删除失败！";
        }
    }

    /**
     * 加载该框架的所有框架项
     * @param sframeId
     * @return
     */
    @RequestMapping("showSframeItemBySframeIdList")
    @ResponseBody
    public List<SframeItemTimeLimit> showSframeItemBySframeIdList(String sframeId){
        System.out.println("===========lsw=========="+sframeId);
        List<ScheduleFrameItem> scheduleFrameItems= scheduleFrameItemService.selectSframeItemBySframeId(Integer.parseInt(sframeId));


        System.out.println("===============scheduleFrameItems===========123112232123213212231231232132====="+scheduleFrameItems);
        List<SframeItemTimeLimit> timelimit=new ArrayList<>();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("hh:mm:ss");
        for (ScheduleFrameItem scheduleFrameItem:scheduleFrameItems) {
            String startTime= simpleDateFormat.format(scheduleFrameItem.getStartTime());
            String stopTime= simpleDateFormat.format(scheduleFrameItem.getStopTime());


            SframeItemTimeLimit sframeItemTimeLimit=new SframeItemTimeLimit();
            sframeItemTimeLimit.setSerialNumber(scheduleFrameItem.getSerialNumber());
            sframeItemTimeLimit.setTimeLimit(startTime+"——"+stopTime);
            sframeItemTimeLimit.setSframeItemId(""+scheduleFrameItem.getSframeItemId());
            timelimit.add(sframeItemTimeLimit);
        }

        System.out.println("===========timelimit============="+timelimit);
        return timelimit;
    }








}




